package org.eiahe.hr.salary.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.ehe.common.core.utils.MapstructUtils;
import org.ehe.common.core.utils.StringUtils;
import org.ehe.common.mybatis.core.page.PageQuery;
import org.ehe.common.mybatis.core.page.TableDataInfo;
import org.ehe.system.domain.vo.SysDeptVo;
import org.ehe.system.service.ISysDeptService;
import org.eiahe.hr.salary.domain.HousingFundPayment;
import org.eiahe.hr.salary.domain.bo.HousingFundPaymentBo;
import org.eiahe.hr.salary.domain.vo.HousingFundPaymentVo;
import org.eiahe.hr.salary.mapper.HousingFundPaymentMapper;
import org.eiahe.hr.salary.service.IHousingFundPaymentService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 公积金缴纳Service业务层处理
 *
 * @author zhangnn
 */
@RequiredArgsConstructor
@Service
public class HousingFundPaymentServiceImpl implements IHousingFundPaymentService {

    private final HousingFundPaymentMapper baseMapper;
    private final ISysDeptService deptService;

    @Override
    public HousingFundPaymentVo queryById(Long paymentId) {
        HousingFundPaymentVo housingFundPaymentVo = baseMapper.selectVoById(paymentId);
        if (null != housingFundPaymentVo.getDepartment()) {
            SysDeptVo sysDeptVo = deptService.selectDeptById(housingFundPaymentVo.getDepartment());
            if (Objects.nonNull(sysDeptVo)) {
                housingFundPaymentVo.setDepartmentName(sysDeptVo.getDeptName());
            }
        }
        return housingFundPaymentVo;
    }

    @Override
    public List<HousingFundPaymentVo> queryList(HousingFundPaymentBo bo) {
        LambdaQueryWrapper<HousingFundPayment> lqw = buildQueryWrapper(bo);
        List<HousingFundPaymentVo> vos = baseMapper.selectVoList(lqw);
        vos.forEach(s -> {
            if (null != s.getDepartment()) {
                SysDeptVo sysDeptVo = deptService.selectDeptById(s.getDepartment());
                if (Objects.nonNull(sysDeptVo)) {
                    s.setDepartmentName(sysDeptVo.getDeptName());
                }
            }
        });
        return vos;
    }

    @Override
    public TableDataInfo<HousingFundPaymentVo> queryPageList(HousingFundPaymentBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<HousingFundPayment> lqw = buildQueryWrapper(bo);
        IPage<HousingFundPaymentVo> page = baseMapper.selectVoPage(pageQuery.build(), lqw);
        page.getRecords().forEach(s -> {
            if (null != s.getDepartment()) {
                SysDeptVo sysDeptVo = deptService.selectDeptById(s.getDepartment());
                if (Objects.nonNull(sysDeptVo)) {
                    s.setDepartmentName(sysDeptVo.getDeptName());
                }
            }
        });
        return TableDataInfo.build(page);
    }

    /**
     * 构建查询条件
     *
     * @param bo 公积金缴纳业务对象
     * @return 查询条件
     */
    private LambdaQueryWrapper<HousingFundPayment> buildQueryWrapper(HousingFundPaymentBo bo) {
        LambdaQueryWrapper<HousingFundPayment> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getEmployeeNo()), HousingFundPayment::getEmployeeNo, bo.getEmployeeNo());
        lqw.eq(StringUtils.isNotBlank(bo.getEmployeeName()), HousingFundPayment::getEmployeeName, bo.getEmployeeName());
        lqw.eq(StringUtils.isNotBlank(bo.getYearMonth()), HousingFundPayment::getYearMonth, bo.getYearMonth());
        lqw.eq(StringUtils.isNotBlank(bo.getPaymentStatus()), HousingFundPayment::getPaymentStatus,
                bo.getPaymentStatus());
        lqw.orderByDesc(HousingFundPayment::getCreateTime);
        return lqw;
    }

    @Override
    public Boolean insertByBo(HousingFundPaymentBo bo) {
        // 自动计算个人和公司缴费金额
        calculatePaymentAmounts(bo);

        HousingFundPayment add = MapstructUtils.convert(bo, HousingFundPayment.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setPaymentId(add.getPaymentId());
        }
        return flag;
    }

    @Override
    public Boolean updateByBo(HousingFundPaymentBo bo) {
        // 自动计算个人和公司缴费金额
        calculatePaymentAmounts(bo);

        // 先查询数据库中的原始数据
        HousingFundPayment oldEntity = baseMapper.selectById(bo.getPaymentId());
        // 转换BO到实体
        HousingFundPayment update = MapstructUtils.convert(bo, HousingFundPayment.class);
        if (oldEntity != null) {
            if (StringUtils.isBlank(bo.getIdCard())) {
                update.setIdCard(oldEntity.getIdCard());
            }
            if (StringUtils.isBlank(bo.getDepartment())) {
                update.setDepartment(oldEntity.getDepartment());
            }
        }
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 自动计算个人和公司缴费金额
     * 个人缴费金额 = 缴费基数 × 个人缴费比例
     * 公司缴费金额 = 缴费基数 × 公司缴费比例
     *
     * @param bo 公积金缴纳业务对象
     */
    private void calculatePaymentAmounts(HousingFundPaymentBo bo) {
        // 计算个人缴费金额
        if (bo.getPaymentBase() != null && bo.getPersonalRate() != null) {
            BigDecimal personalAmount = bo.getPaymentBase().multiply(bo.getPersonalRate())
                .divide(new BigDecimal("100"), 4, BigDecimal.ROUND_HALF_UP)
                .setScale(2, BigDecimal.ROUND_HALF_UP);
            bo.setPersonalAmount(personalAmount);
        }

        // 计算公司缴费金额
        if (bo.getPaymentBase() != null && bo.getCompanyRate() != null) {
            BigDecimal companyAmount = bo.getPaymentBase().multiply(bo.getCompanyRate())
                .divide(new BigDecimal("100"), 4, BigDecimal.ROUND_HALF_UP)
                .setScale(2, BigDecimal.ROUND_HALF_UP);
            bo.setCompanyAmount(companyAmount);
        }
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(HousingFundPayment entity) {
        // TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
